from django.core.management.base import BaseCommand
from django.db import transaction
from api.models import Food, Order
import logging

logger = logging.getLogger('api')

class Command(BaseCommand):
    help = '更新所有食品的销量数据，基于已完成的订单'

    def handle(self, *args, **options):
        try:
            with transaction.atomic():
                # 重置所有食品的销量为0
                Food.objects.all().update(sold=0)
                self.stdout.write(self.style.SUCCESS("已重置所有食品销量为0"))
                
                # 获取所有已完成的订单
                completed_orders = Order.objects.filter(status='completed')
                self.stdout.write(f"找到 {completed_orders.count()} 个已完成订单")
                
                # 创建一个字典来累计每个食品的销量
                food_sold_count = {}
                
                # 遍历所有已完成订单的订单项
                for order in completed_orders:
                    order_items = order.items.all()
                    
                    for item in order_items:
                        food_id = item.food.id
                        count = item.count
                        
                        if food_id in food_sold_count:
                            food_sold_count[food_id] += count
                        else:
                            food_sold_count[food_id] = count
                
                # 更新食品销量
                for food_id, sold_count in food_sold_count.items():
                    food = Food.objects.get(id=food_id)
                    food.sold = sold_count
                    food.save()
                    self.stdout.write(f"更新食品 {food.name}(ID:{food_id}) 销量为 {sold_count}")
                
                self.stdout.write(self.style.SUCCESS(f"成功更新 {len(food_sold_count)} 个食品的销量"))
        except Exception as e:
            logger.error(f"更新食品销量失败: {str(e)}")
            self.stdout.write(self.style.ERROR(f"更新食品销量失败: {str(e)}"))
            return 